package com.hc.action;

import com.hc.domain.Good;
import com.hc.mapper.GoodMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoodActionImpl implements GoodAction {
    @Autowired
    private GoodMapper goodMapper;

    @Override
    public void tryGood(BusinessActionContext context, int goodId, int num) {
        Good good = goodMapper.findGoodById(goodId);
        if (good.getGoodStock() < num) {
            throw new RuntimeException("库存不⾜");
        }
        System.out.println("good的try⽅法执⾏了");
        goodMapper.reduceStock(goodId, num);
    }

    @Override
    public void commit(BusinessActionContext context) {
        System.out.println("good的commit⽅法执⾏了");
        int goodId = context.getActionContext("goodId", Integer.class).intValue();

        int num = context.getActionContext("num", Integer.class).intValue();
        goodMapper.commitStock(goodId, num);
    }

    @Override
    public void rollback(BusinessActionContext context) {
        System.out.println("good的rollback⽅法执⾏了");
        int goodId = context.getActionContext("goodId", Integer.class).intValue();
        int num = context.getActionContext("num", Integer.class).intValue();
        goodMapper.cancelStock(goodId, num);
    }
}